package com.example.gateway.config;

import com.example.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component
public class JwtAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtAuthGatewayFilterFactory.Config> {

    @Value("${jwt.secret}")
    private String secret;

    private static final List<String> DEFAULT_EXCLUDE_PATHS = Arrays.asList(
            "/auth/login",
            "/auth/validate",
            "/login"
    );

    @Autowired
    JwtUtil jwtUtil;

    public JwtAuthGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getPath().toString();
            System.out.println(request.getRemoteAddress() + "请求路径: " + path);

            // 检查是否为排除路径
            if (config.getExcludePaths() != null && !config.getExcludePaths().isEmpty()) {
                for (String excludePath : config.getExcludePaths()) {
                    System.out.println(path.startsWith(excludePath) + "检查排除路径: " + excludePath);
                    if (path.startsWith(excludePath)) {
                        return chain.filter(exchange);
                    }
                }
            } else {
                for (String excludePath : DEFAULT_EXCLUDE_PATHS) {
                    if (path.startsWith(excludePath)) {
                        return chain.filter(exchange);
                    }
                }
            }

            String token = getJwtFromRequest(request);
            if (token == null) {
                return onError(exchange, "No authorization header", HttpStatus.UNAUTHORIZED);
            }
            System.out.println("请求token: " + token);

            try {
                if (!isJwtValid(token)) {
                    return onError(exchange, "Invalid JWT token", HttpStatus.UNAUTHORIZED);
                }
            } catch (Exception e) {
                return onError(exchange, "JWT token validation error", HttpStatus.UNAUTHORIZED);
            }

            if (token != null) {
                try {
                    // 检查并续期Token
                    String newToken = jwtUtil.generateOrRenewToken(token);

                    // 如果Token被续期，添加到响应头
                    if (!newToken.equals(token)) {
                        ServerHttpResponse response = exchange.getResponse();
                        response.getHeaders().add("X-Renewed-Token", newToken);
                    }
                } catch (Exception e) {
                    // Token无效，继续流程（后续认证过滤器会处理）
                }
            }


            return chain.filter(exchange);
        }, Ordered.HIGHEST_PRECEDENCE);  // 设置为最高优先级
    }

    private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(httpStatus);
        return response.setComplete();
    }

    private String getJwtFromRequest(ServerHttpRequest request) {
        String bearerToken = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    private boolean isJwtValid(String jwt) {
        try {
            System.out.println("Validating token: " + jwt);
            SecretKey key = Keys.hmacShaKeyFor(secret.getBytes());
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(jwt)
                    .getBody();

            System.out.println("Token claims: " + claims);
            return !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            System.out.println("Token validation failed: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Data
    public static class Config {
        // 必须使用 List<String> 接收
        private List<String> excludePaths;
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("excludePaths");
    }
}